package main

import (
	"context"
	"fmt"
	sp "gitee.com/wxy365/sprout"
)

func main() {
	app := sp.NewAppBuilder[*DemoAppCtx]().AddServerBuilder(
		sp.NewServerBuilder().
			Name("demo server").
			AddEndpoint(&demoEndpoint{}),
	).Name("demo app").Build()
	app.Run()
}

type demoEndpoint struct {
	sp.BaseEndpoint
}

func (d *demoEndpoint) Name() string {
	return "demo"
}

func (d *demoEndpoint) Pattern() string {
	return "/demo/{id:~[0-9]+}/{name}"
}

func (d *demoEndpoint) Methods() []string {
	return []string{"GET", "POST"}
}

func (d *demoEndpoint) Handler() sp.Handler {
	return func(ctx context.Context, in any, out any) error {
		inEntry := in.(*DemoIn)
		outEntry := out.(*DemoOut)
		outEntry.Message = fmt.Sprintf("%d:%s:%v", inEntry.Id, inEntry.Name, inEntry.Hobbies)
		return nil
	}
}

func (d *demoEndpoint) InputEntity() any {
	return &DemoIn{
		Name: "wxy",
		Id:   12349876,
	}
}

func (d *demoEndpoint) OutputEntity() any {
	return &DemoOut{}
}

func (d *demoEndpoint) Interceptors() []string {
	return []string{}
}

type DemoIn struct {
	Name    string   `path:"name"`
	Id      int64    `path:"id"`
	Hobbies []string `query:"hobbies"`
}

type DemoOut struct {
	Message string `json:"message"`
}

type DemoAppCtx struct {
	Ins []DemoIn `env:"DEMO_APP_INS" default:"[{\"id\":123, \"name\":\"xixi\"}]"`
}
